package com.glsc.ngateway.opmanage.controller.other;


import com.glsc.ngateway.common.api.platform.dto.other.TradeSeatRentDto;
import com.glsc.ngateway.opmanage.service.other.TradeSeatRentService;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.common.ex.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author: zzp
 * @Date: 2022/6/6
 * @Desc: 交易单元租用信息表
 */
@RestController
@RequestMapping("/api/tradeSeatRentInfo/")
@Api(value = "TradeSeatRentController", tags = {"交易单元信息管理"})
public class TradeSeatRentController {

    private static Logger logger = LoggerFactory.getLogger(TradeSeatRentController.class);

    @Resource
    private TradeSeatRentService tradeSeatRentService;

    @GetMapping("/listpage")
    @ApiOperation(value = "交易单元租用信息分页查询", notes = "交易单元租用信息分页查询")
    public Result<Page<TradeSeatRentDto>> listPage(@ApiParam(value = "交易单元号") @RequestParam(required = false) String tradeSeatCode,
                                                   @ApiParam(value = "市场") @RequestParam(required = false) String tradeSeatMarket,
                                                   @ApiParam(value = "申请部门") @RequestParam(required = false)  String applyDeptName,
                                                   @ApiParam(value = "使用机构名称") @RequestParam(required = false)  String useCompanyName,
                                                   @ApiParam(value = "交易单元性质 字典: am_trade_seat_use_type") @RequestParam(required = false) String useType,
                                                   @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
                                                   @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
        Page<TradeSeatRentDto> page = tradeSeatRentService.findPage(tradeSeatCode, tradeSeatMarket,applyDeptName,useType, useCompanyName, PageUtil.initPageNo(pageNo), PageUtil.initPageSize(pageSize));
        return Result.successData(page);
    }

    /*
     * 前端统一操作，/create 为新增
     * */
    @PostMapping("/create")
    @ApiOperation(value = "创建交易单元租用信息", notes = "创建交易单元租用信息")
    public Result save(@ApiParam(required = true, value = "交易单元租用信息") @RequestBody TradeSeatRentDto tradeSeatRentDto) {
        logger.info("创建交易单元租用信息：" + tradeSeatRentDto);
        TradeSeatRentDto tradeSeatRentDtoSaved = tradeSeatRentService.saveOrUpdate(tradeSeatRentDto);
        return Result.successData("创建成功");

    }

    /*
     * 前端统一操作，/update 为修改
     * */
    @PostMapping("/update")
    @ApiOperation(value = "更新交易单元租用信息", notes = "更新交易单元租用信息")
    public Result update(@ApiParam(required = true, value = "交易单元租用信息") @RequestBody TradeSeatRentDto tradeSeatRentDto) {
        logger.info("更新交易单元租用信息：" + tradeSeatRentDto);

        TradeSeatRentDto tradeSeatRentDtoSaved = tradeSeatRentService.saveOrUpdate(tradeSeatRentDto);
        return Result.successData("更新成功");
    }

    /*
     * 自适应新增和修改
     * */
    @GetMapping("/saveOrUpdate")
    @ApiOperation(value = "交易单元租用信息保存", notes = "交易单元租用信息保存")
    public Result<TradeSeatRentDto> saveOrUpdate(@ApiParam(value = "交易单元租用信息") @RequestParam(required = false) TradeSeatRentDto tradeSeatRentDto) {
        TradeSeatRentDto tradeSeatRentDtoSaved = tradeSeatRentService.saveOrUpdate(tradeSeatRentDto);
        return Result.successData(tradeSeatRentDtoSaved);
    }

//    @PostMapping("/importTradeSeatRentInfo")
//    @ApiOperation(value = "批量导入交易单元租用信息", notes = "批量导入交易单元租用信息")
//    public Result<List<TradeSeatHistoryDto>> importTradeSeatInfoFromExcel(MultipartFile file) throws IOException {
//        try {
//            String oFileName = file.getOriginalFilename();
//            logger.info("批量导入交易单元租用信息文件:{}", file.getOriginalFilename());
//            if (file.isEmpty()) {
//                throw AmException.error("批量导入交易单元租用信息Excel文件为空");
//            }
//            String destFileName = Constant.PROD_DOC_ROOT_DIR + CommonUtils.getDateStr(new Date(), DictConstant.FORMAT_DATE_YYYYMMDD)
//                    + File.separator + UUID.randomUUID() + File.separator + oFileName;//增加uuid层，解决上传文件名重复问题
//            File destFile = new File(documentInfoService.getUploadRoot() + destFileName);
//            FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
//
//            TradeSeatRentInfoReader tradeSeatRentInfoReader = new TradeSeatRentInfoReader();
//            EasyExcel.read(destFile, TradeSeatRentInfoImportDto.class, tradeSeatRentInfoReader).sheet("交易单元租用信息").doRead();
//            List<TradeSeatRentInfoImportDto> importData = tradeSeatRentInfoReader.getTradeSeatRentInfoImportDtoList();
//            logger.info("批量导入交易单元租用信息Excel文件中提供了{}条记录", importData.size());
//            List<TradeSeatRent> tradeSeatRentInfoList = new ArrayList<>();
//            if (CollectionUtil.isNotEmpty(importData)) {
//
//                //获取交易单元市场字典map
//                Map<String, String> tradeSeatMarketDictMap = CacheManager.getDictFromRedis(DictConstant.DICT_CODE_TRADE_SEAT_MARKET).getDictValues().stream().collect(
//                        Collectors.toMap(DictValue::getLabel, DictValue::getValue));
//                //获取交易单元类型字典map
//                Map<String, String> tradeSeatUseTypeDictMap = CacheManager.getDictFromRedis(DictConstant.DICT_CODE_TRADE_SEAT_USE_TYPE).getDictValues().stream().collect(
//                        Collectors.toMap(DictValue::getLabel, DictValue::getValue));
//                //获取交易单元状态字典map
//                Map<String, String> tradeSeatStateDictMap = CacheManager.getDictFromRedis(DictConstant.DICT_CODE_TRADE_SEAT_STATE).getDictValues().stream().collect(
//                        Collectors.toMap(DictValue::getLabel, DictValue::getValue));
//
//                String importKey = CommonUtils.getDateStr(new Date(), DictConstant.FORMAT_DATE_YYYYMMDD) + UUID.randomUUID();
//                importData.forEach(item -> {
//                    TradeSeatRent tradeSeatRentInfo = new TradeSeatRent();
//                    BeanUtil.copyProperties(item, tradeSeatRentInfo);
//                    tradeSeatRentInfo.setImportKey(importKey);
//                    tradeSeatRentInfo.setTradeSeatMarket(tradeSeatMarketDictMap.get(tradeSeatRentInfo.getTradeSeatMarket()));
//                    tradeSeatRentInfo.setUseType(tradeSeatUseTypeDictMap.get(tradeSeatRentInfo.getUseType()));
//                    tradeSeatRentInfo.setState(tradeSeatStateDictMap.get(tradeSeatRentInfo.getState()));
//                    tradeSeatRentInfoList.add(tradeSeatRentInfo);
//                });
//            }
//            tradeSeatRentService.saveTradeSeatRentList(tradeSeatRentInfoList);
//            return Result.successData(tradeSeatRentInfoList);
//        } catch (Exception e) {
//            logger.error("批量导入交易单元租用信息Excel文件失败:", e);
//            return Result.failData("批量导入交易单元租用信息Excel文件失败:" + e.getMessage());
//        }
//    }

    @GetMapping("/downloadTemplateFile")
    @ApiOperation(value = "下载交易单元信息模板文件")
    public void downloadTemplateFile(HttpServletResponse response) throws UnsupportedEncodingException {
        //强制下载不打开
        response.setContentType("application/force-download");
        //使用URLEncoder来防止文件名乱码或者读取错误
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("交易单元租用信息导入模板.xlsx", "UTF-8"));
        try (InputStream input = this.getClass().getResourceAsStream("/exceltemplates/trade_seat_rent_template.xlsx")) {
            OutputStream output = response.getOutputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(input);
            workbook.write(output);
            workbook.close();
        } catch (IOException e) {
            logger.error("Error", e);
        }
    }
}
